package cn.edu.jxau.test;

import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;

public class Main {

	public static void main(String[] args) throws IOException {

		Main m = new Main();

		System.out.println(
				Arrays.deepToString(m.transformImage(new int[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }, 3)));
	}

	//-----------------------------------
	// 解法一
	//-----------------------------------
	public int[][] transformImage(int[][] mat, int n) {

		// 1.参数校验 //
		Objects.requireNonNull(mat, "参数mat是否为null");
		if (mat.length != n) {
			throw new IllegalArgumentException("参数mat不是n*n矩阵");
		}
		for (int i = 0; i < mat.length; i++) {
			if (mat[i].length != n) {
				throw new IllegalArgumentException("参数mat不是n*n矩阵");
			}
		}
		// 2.transform //
		transformImage(mat, 0, 0, n);
		return mat;
	}

	public void transformImage(int[][] mat, int i, int j, int n) {

		if (n <= 1) {
			return;
		}
		int[] temp = new int[n];
		int p = j;
		for (int m = 0; m < temp.length; m++) {
			temp[m] = mat[i][p++];
		}
		// 坐标体系如下
		//
		// (i,j)
		// *____________________x
		// |
		// |
		// |
		// |
		// |
		// |
		// |
		// |
		// y
		//
		//

		// 1.右->上 //
		int x1 = j;
		int y1 = i;
		int x2 = j + n - 1;
		int y2 = i;
		for (int k = 0; k < n; k++) {
			mat[y2][x2] = mat[y1][x1];
			y1++;
			x2--;
		}
		System.out.println(Arrays.deepToString(mat));
		// 2.下->右 //
		x1 = j + 1;
		y1 = i + n - 1;
		x2 = j;
		y2 = i + 1;
		for (int k = 0; k < n - 1; k++) {
			mat[y2][x2] = mat[y1][x1];
			x1++;
			y2++;
		}
		System.out.println(Arrays.deepToString(mat));
		// 3.左->下 //
		x1 = j + n - 1;
		y1 = i + n - 2;
		x2 = j + 1;
		y2 = i + n - 1;
		for (int k = 0; k < n - 1; k++) {
			mat[y2][x2] = mat[y1][x1];
			y1--;
			x2++;
		}
		System.out.println(Arrays.deepToString(mat));
		// 4.temp->左 //
		x2 = j + n - 1;
		y2 = i + 1;
		for (int k = 1; k < temp.length; k++) {
			mat[y2][x2] = temp[k];
			y2++;
		}
		System.out.println(Arrays.deepToString(mat));
		transformImage(mat, i + 1, j + 1, n - 2);
	}
	

	//-----------------------------------
	// 解法二
	//-----------------------------------
//	public int[][] transformImage(int[][] mat, int n) {
//
//		for (int layer = 0; layer < n - 2; layer++) {
//			int first = layer;
//			int last = n - 1 - layer;
//			for (int i = first; i < last; i++) {
//				int offset = i - first;
//				int top = mat[first][i];
//				mat[first][i] = mat[last - offset][first];
//				mat[last - offset][first] = mat[last][last - offset];
//				mat[last][last - offset] = mat[i][last];
//				mat[i][last] = top;
//			}
//		}
//		return mat;
//	}
}